package com.COMP3111H.project;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class SearchResult extends ListActivity {
	final int HELP = 0;

	private List<Map<String, Object>> mData;

	ProgressDialog progDialog;
	ProgressThread progThread;
	Button menu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_list_main);
		
		mData = getData(this.getIntent().getExtras().getString("data"));
		View footerView = ((LayoutInflater) this
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(
				R.layout.search_list_footer, null, false);
		this.getListView().addFooterView(footerView);
		Button sellNewBook = (Button) findViewById(R.id.sellnewbook);

		sellNewBook.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent i = new Intent(SearchResult.this,
						SellLend_New_Book.class);
				startActivity(i);
			}
		});

		this.getListView().setCacheColorHint(0);
		this.getListView().setBackgroundColor(0);

		MyAdapter adapter = new MyAdapter(this);
		setListAdapter(adapter);
		menu = (Button) findViewById(R.id.searchlist_menu);
	}
	
	@Override
    protected void onResume() {
		super.onResume();
		if (LoginUtility.checkLoginStatus(this)) {
			menu.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					 String[] choices={"Home","View My Profile","Help","Cancel"};  
					             AlertDialog dialog = new AlertDialog.Builder(SearchResult.this)  
					                     // .setIcon(android.R.drawable.btn_star)  
					                      .setTitle("Menu")  
					                      .setItems(choices, onselect_logged).create();  
					             dialog.show();  
				}
			});
		}
		else{
			menu.setOnClickListener(new View.OnClickListener() {
				public void onClick(View v) {
					 String[] choices={"Home","Help","Cancel"};  
					             AlertDialog dialog = new AlertDialog.Builder(SearchResult.this)  
					                     // .setIcon(android.R.drawable.btn_star)  
					                      .setTitle("Menu")  
					                      .setItems(choices, onselect_not_logged).create();  
					             dialog.show();  
				}
			});
		}
	}

	OnClickListener onselect_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(SearchResult.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(SearchResult.this, My_Profile.class);
				startActivity(myIntent);
				break;
			case 2:
				myIntent = new Intent(SearchResult.this, Help.class);
				startActivity(myIntent);
				break;
			case 3:
				dialog.dismiss();
				break;
			}
		}
	};
	
	OnClickListener onselect_not_logged = new OnClickListener() {
		public void onClick(DialogInterface dialog, int which) {
			// TODO Auto-generated method stub
			Intent myIntent;
			switch (which) {
			case 0:
				myIntent = new Intent(SearchResult.this, Home.class);
				startActivity(myIntent);
				break;
			case 1:
				myIntent = new Intent(SearchResult.this, Help.class);
				startActivity(myIntent);
				break;
			case 2:
				dialog.dismiss();
				break;
			}
		}
	};
	
	private List<Map<String, Object>> getData(String data) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map;
		// TODO

		try {
			JSONArray jArray = new JSONArray(data);
			JSONObject json_data = null;
			int length = jArray.length();
			for (int i = 0; i < length; i++) {
				json_data = jArray.getJSONObject(i);
				map = new HashMap<String, Object>();
				map.put("title", json_data.getString("Title"));
				map.put("edition", json_data.getString("Edition"));
				map.put("courses", json_data.getString("Courses"));
				map.put("authors", json_data.getString("Authors"));
				map.put("publishers", json_data.getString("Publisher"));
				map.put("ISBN", json_data.getString("ISBN"));
				map.put("copies", json_data.getString("Copies"));
				list.add(map);
			}
		} catch (JSONException e) {
			throw new RuntimeException(e);
		}

		return list;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		showDialog(0);
		progThread = new ProgressThread(handler, position);
		progThread.start();

	}

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: // Spinner
			progDialog = new ProgressDialog(this);
			progDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
			progDialog.setMessage("Loading...");

			return progDialog;
		default:
			return null;
		}
	}

	final Handler handler = new Handler() {
		public void handleMessage(Message msg) {

			String returnedData = msg.getData().getString("returnedData");
			removeDialog(0);

			Intent myIntent = new Intent(SearchResult.this,
					ViewBookDetailsTab.class);
			myIntent.putExtra("data", returnedData);
			startActivity(myIntent);
		}

	};

	private class ProgressThread extends Thread {
		int position;
		Handler mHandler;

		ProgressThread(Handler h, int p) {
			mHandler = h;
			position = p;
		}

		@Override
		public void run() {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair("input", (String) mData.get(position).get("ISBN")));
			String returnedData = NetworkUtility.sendHTTP(params,
							"http://webproject2.cse.ust.hk:8029/BookwarmMobile/jsp/isbnsearch.jsp");

			Message msg = mHandler.obtainMessage();
			Bundle b = new Bundle();
			b.putString("returnedData", returnedData);
			msg.setData(b);
			mHandler.sendMessage(msg);

		}
	}

	public class MyAdapter extends BaseAdapter {

		private LayoutInflater mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		public final class ViewHolder {
			public TextView title;
			public TextView edition;
			public TextView courses;
			public TextView authors;
			public TextView publishers;
			public TextView ISBN;
			public TextView copies;
		}

		public View getView(int position, View convertView, ViewGroup parent) {

			ViewHolder holder = null;
			if (convertView == null) {
				holder = new ViewHolder();

				convertView = mInflater.inflate(R.layout.search_list, null);
				holder.title = (TextView) convertView.findViewById(R.id.title);
				holder.edition = (TextView) convertView
						.findViewById(R.id.edition);
				holder.courses = (TextView) convertView
						.findViewById(R.id.course);
				holder.authors = (TextView) convertView
						.findViewById(R.id.authors);
				holder.publishers = (TextView) convertView
						.findViewById(R.id.publishers);
				holder.ISBN = (TextView) convertView.findViewById(R.id.ISBN);
				holder.copies = (TextView) convertView
						.findViewById(R.id.copies);
				convertView.setTag(holder);

			} else {
				holder = (ViewHolder) convertView.getTag();
			}

			holder.title.setText((String) mData.get(position).get("title"));
			holder.edition.setText((String) mData.get(position).get("edition"));
			holder.courses.setText((String) mData.get(position).get("courses"));
			holder.authors.setText((String) mData.get(position).get("authors"));
			holder.publishers.setText((String) mData.get(position).get(
					"publishers"));
			holder.ISBN.setText((String) mData.get(position).get("ISBN"));
			holder.copies.setText((String) mData.get(position).get("copies"));
			return convertView;
		}

	}
}
